<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-form-item prop="content" ref="content">
      <el-input v-show="false" v-model="form.content" />
      <ckeditor ref="ckeditor" class="h-small" :content.sync="form.content" />
    </el-form-item>
    <el-form-item v-if="currentUser.admin">
      <el-radio-group v-model="form.state">
        <el-radio label="waiting" disabled>待受理</el-radio>
        <el-radio label="accepted">已受理</el-radio>
        <el-radio label="processing">处理中</el-radio>
        <el-radio label="resolved" disabled>已解决</el-radio>
        <el-radio label="confirming" disabled>待确认</el-radio>
        <el-radio label="closed" disabled>已关闭</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" :loading="loading">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { formatFeedback } from '../format';

export default {
  name: 'reply', // 回复反馈
  data() {
    return {
      form: {
        content: '',
        state: this.$store.state.currentFeedback.state,
      },
      rules: {
        content: { validator: this.$va.content },
      },
      loading: false,
    };
  },
  computed: {
    ...mapState(['currentUser']),
    // 当回复人不是管理员，且状态为待确认时，自动标记为‘处理中’
    autoState() {
      if (!this.currentUser.admin && this.form.state === 'confirming') return 'processing';
      return this.form.state;
    },
  },
  methods: {
    ...mapActions(['setCurrentFeedback']),
    onSubmit() {
      this.$refs.form.validate((valid, errs) => {
        if (valid) {
          this.loading = true;
          this.$api.feedback.reply({
            feedbackId: this.$route.params.feedbackId,
            content: this.form.content,
            timestamp: new Date().getTime(),
            state: this.autoState,
          }).then((res) => {
            this.$refs.form.resetFields();
            this.$refs.ckeditor.clearContent();
            this.setCurrentFeedback(formatFeedback(res.data));
            this.$message.success('发送成功');
          }).catch(() => {})
            .then(() => { this.loading = false; });
        } else this.$refs[Object.keys(errs)[0]].$el.scrollIntoView({ block: 'center' });
      });
    },
  },
};
</script>

<style></style>
